package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;

/**
 * @Author wy
 * @Date 2021/3/2 15:33
 * @Version 1.0
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //定义随机队列
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue,false,true,true,null);
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);


        System.out.println("输入绑定键,用空格隔开:");
        String s = new Scanner(System.in).nextLine();//里面有多个键
        String[] a = s.split("\\s+");
        for (String key : a) {
            c.queueBind(queue,"topic_logs",key);
        }
        //从随机队列正常消费数据
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String key = message.getEnvelope().getRoutingKey();
                String s = new String(message.getBody());
                System.out.println(key+" - 收到： "+s);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        // 消费数据
        c.basicConsume(queue, true, deliverCallback, cancelCallback);
    }



    }


